from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.template import RequestContext
from django import forms
from django.core.urlresolvers import reverse
from django.contrib.sitemaps import Sitemap
from datetime import datetime, timedelta

def log_in(request):
	username = request.POST['username']
	password = request.POST['password']
	user = authenticate(username=username, password=password)
	if user is not None:
		if user.is_active:
				login(request, user)
				if request.GET:
					if request.GET.get('next'):
						next = request.GET['next']
						return HttpResponseRedirect(next)
				return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
		else:
			return HttpResponseRedirect('http://fblaconnection.com/login/?status=na')
	else:
		return HttpResponseRedirect('http://fblaconnection.com/login/?status=fail')

def log_out(request):
	logout(request)
	return HttpResponseRedirect('http://fblaconnection.com/login/?status=logout')

def log_in_view(request):
	if (request.user.is_authenticated()):
		return HttpResponseRedirect('http://fblaconnection.com/panel/'+ request.user.username + '/')
	else:
		context = {}
		if request.POST:
			username = request.POST['username']
			context = {
				'username' : username
			}
		if request.GET:
			if request.GET.get('next'):
				next = request.GET['next']
			else:
				next = None
			context.update({
				'next' : next,
			})
			if request.GET.get('status'):
				error_message = False
				na_error = False
				in_error = False
				log_out = False
				status = request.GET['status']
				if status == "fail":
					status = "Failed"
					in_error = True
					error_message = True
				if status == "na":
					status = "Failed"
					na_error = True
					error_message = True
				if status == "logout":
					status = None
					log_out = True
					error_message = True
				context.update({
					'status' : status,
					'error_message' : error_message,
					'in_error' : in_error,
					'na_error' : na_error,
					'log_out' : log_out,
				})
		return render_to_response('login/login.html', context, context_instance = RequestContext(request))